How to use appsettings.json in Asp.net core?
How to use appsettings.json in Asp.net core?
443
06-Jul-2023
Updated on 07-Jul-2023
Aryan Kumar
07-Jul-2023The
appsettings.jsonfile is used to store configuration settings for an ASP.NET Core application. These settings can be used to configure anything from database connection strings to application secrets.To use the
appsettings.jsonfile, you first need to add it to your project. You can do this by right-clicking on your project in Solution Explorer and selecting Add > New Item. From the list of templates, select App Settings File and click Add.Once the
appsettings.jsonfile has been added, you can start adding configuration settings to it. Each setting is defined as a key-value pair. The key is the name of the setting and the value is the value of the setting.For example, to define a database connection string, you would add the following setting to the
appsettings.jsonfile:Code snippet
Once you have added your configuration settings to the
appsettings.jsonfile, you can access them in your code using theIConfigurationservice. TheIConfigurationservice is provided by the ASP.NET Core framework and it can be injected into your classes using dependency injection.To access a configuration setting, you can use the
GetSection()method. TheGetSection()method takes the name of the section as its parameter and returns anIConfigurationSectionobject. TheIConfigurationSectionobject contains all of the settings in the specified section.For example, to get the database connection string, you would use the following code:
Code snippet
The
connectionStringvariable will now contain the value of theDefaultConnectionsetting in theConnectionStringssection of theappsettings.jsonfile.You can also use the
IConfigurationservice to get individual configuration settings by using theGetValue()method. TheGetValue()method takes the name of the setting and the default value as its parameters. If the setting is not found in the configuration file, the default value will be returned.For example, to get the value of the
MySettingsetting, you would use the following code:Code snippet
The
valuevariable will now contain the value of theMySettingsetting, or the default value if the setting is not found in the configuration file.